import React, { Component } from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Icon,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
  Input,
  Divider,
  Popconfirm,
  Modal,
  InputNumber,
  message,
  List
} from 'antd';
import { connect } from 'dva';
const { MonthPicker, RangePicker } = DatePicker;
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import numeral from 'numeral';
import { formatMessage, FormattedMessage } from 'umi/locale';
import moment from 'moment';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const { Search, TextArea } = Input;
import {
  ChartCard,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
  TimelineChart,
} from '@/components/Charts';

const { Meta } = Card;

import Trend from '@/components/Trend';
import styles from './vip.less';

import { getValueWithLocalStorage } from '@/utils/authority';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

const namespace = 'vip';
import router from 'umi/router';
import config from '../../../config/web.config'

import {routerRedux} from 'dva/router';



const userInfo = getValueWithLocalStorage('userinfo');

const mapStateToProps = state => {

  const templateList = state[namespace].templateList;
  const list = state[namespace].vipList
  const total = state[namespace].vipLisTotal;
  const isLoading = state[namespace].isLoading;

  return {
    templateList,
    list,
    total,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getServicesTempaltes: (_key, _page, _pagesize,_owner) => {
      const action = {
        type: `${namespace}/getServicesTempaltes`,
        payload: {
          key: _key,
          page: _page,
          pagesize: _pagesize,
          owner:_owner,
        },
      };
      dispatch(action);
    },


    getVipCardList: (_key, _page, _pagesize,_owner) => {
    const action = {
      type: `${namespace}/getVipCardList`,
      payload: {
        key: _key,
        page: _page,
        pagesize: _pagesize,
        owner:_owner,
        type:0,
      },
    };
     dispatch(action);
   },

    updateVipCard:(para,callback) => {
      const action = {
        type: `${namespace}/updateVipCard`,
        payload: {
          ...para,
          callback:callback,
        },
      };
      dispatch(action);
    },

    addVipCardHistory:(para) => {
      const action = {
        type: `${namespace}/addVipCardHistory`,
        payload: {
          ...para,
        },
      };
      dispatch(action);
    },

    delVipCard:(_id,callback) => {
      const action = {
        type: `${namespace}/delVipCard`,
        payload: {
          id:_id,
          callback:callback
        },
      };
      dispatch(action);
    },

    getShopInfo:(_tel,callback) => {
      const action = {
        type: `${namespace}/getShopInfo`,
        payload: {
          tel:_tel,
          callback:callback
        },
      };
      dispatch(action);
    },

    addPackage:(para,callback)=>{
      const action = {
        type: `${namespace}/addPackage`,
        payload: {
          ...para,
          callback:callback
        },
      };
      dispatch(action);
    },

    delOneServiceItem:(para,callback)=>{
      const action = {
        type: `${namespace}/delOneServiceItem`,
        payload: {
          ...para,
          callback:callback
        },
      };
      dispatch(action);
    }
  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class VipCardList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      state: '-1', //维修状态:0维修中 1待结账 2已完成 3已取消
      page: '0',
      pagesize: '3',
      key: this.props.location.query.key  == undefined ? '':this.props.location.query.key,
      isShowInoutMoneyModal:false,
      isShowAddTcModal:false,
      optmoney:0,
      givemoney:0,
      card:undefined,
      shopTel:this.props.location.query.shop  == undefined ? userInfo.tel:this.props.location.query.shop,
      addPackageItem:undefined,
    };
  }

  componentDidMount() {
    config.loadlCNZZ()
    this.reloadData();
    this.props.getServicesTempaltes('','0','100',this.state.shopTel)
  }

  reloadData= ()=>{
    this._getVipCardList()
  }


  _getVipCardList = () => {
    this.props.getVipCardList(
      this.state.key,
      this.state.page,
      this.state.pagesize,
      this.state.shopTel
    );
  };


  render() {

    var that = this;

    const extraContent = (
      <Row>
        <Col span={18}>
          <Search className={styles.extraContentSearch}
                  placeholder="输入用户名/号码/车牌"
                  enterButton
                  all
                  defaultValue={that.state.key}
                  onSearch={(v,e)=>{
                    that.setState({key:v,page:'0'},()=>{
                      that.reloadData()
                    })
                  }} />
        </Col>
        <Col span={2}>
          <span></span>
        </Col>
        <Col span={3}>
          <Link className={styles.addBtn} to={{ pathname:userInfo == null ? '/vip-client/add':'/vip/add', query: {shop:that.state.shopTel}}}><Button type="primary">开卡</Button></Link>
        </Col>
      </Row>
    );


    const columns = [
      {
        title: '会员',
        dataIndex: 'cardNumber',
        width:20,
        key: 'cardNumber',
      },
      {
        title: '余额',
        dataIndex: 'totalMoney',
        width:40,
        key: 'totalMoney',
      },
      {
        title: '卡内套餐',
        dataIndex: 'packageItems',
        key: 'packageItems',
        width:160,
        render: (text, record) => (
          <div className={styles.vip1}>
            {record.packageItems.map(item=>{
              return (<div >
                <Row>
                  <Col span={12}>
                    <span className={styles.lab0}> {item.name}</span>
                  </Col>
                  <Col span={12}>
                    <Popconfirm
                      title="确认删除此服务套餐?"
                      onConfirm={() => {
                          that.props.delOneServiceItem({cardId:record._id,packageId:item._id},res=>{
                            if(res.code == 1){
                              message.success(res.msg)
                              that._getVipCardList()
                            }
                          })
                      }}
                      okText="确认"
                      cancelText="取消"
                    >
                    <Button type="primary" size={"small"}>x</Button>
                    </Popconfirm>
                  </Col>
                </Row>
                <List
                  dataSource={item.serviceitems}
                  renderItem={cell => (<span>
                <Row>
                  <Col span={12}>
                    <span className={styles.lab1}>{cell.name}</span>
                  </Col>
                  <Col span={12}>
                    <span className={styles.lab2}>x{cell.num}</span>
                  </Col>
                </Row>

                </span>)}
                />
                     </div>)
            })
            }
          </div>
        )
      },

      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width:50,
        render: (text, record) => (
          <Route>
            <span>
               <Popconfirm
                 title="确认删除此会员卡?"
                 onConfirm={() => {
                   that.props.delVipCard(record._id,res=>{
                     if(res.code == 1){
                       message.success(res.msg)
                       that._getVipCardList()
                     }
                   })
                 }}
                 okText="确认"
                 cancelText="取消"
               >
                 <div
                   className={styles.actionRow}
                 >
                删除
              </div>
               </Popconfirm>
              <div
                className={styles.actionRow1}
                onClick={()=>{
                  that.setState({isShowInoutMoneyModal:true,card:record})
                }}
              >
                充值
              </div>
              <div
                  className={styles.actionRow1}
                  onClick={()=>{
                    that.setState({isShowAddTcModal:true,card:record})
                  }}
                >
                套餐
              </div>
                <div
                  className={styles.actionRow1}
                >
                <Link  className={styles.actionRow1} to={{ pathname: userInfo == null ?'/vip-client/cardHistory': '/vip/cardHistory', query: {shop:that.state.shopTel,cardId:record.cardId} }}>流水</Link>
              </div>
            </span>
          </Route>
        ),
      },
    ];

    return (
      <Card
        bordered={false}
        style={{ marginTop: 0 }}
        bodyStyle={{ padding: '0 0px 0px 0px' }}
        extra={extraContent }
      >
      <div>
        <Table
          columns={columns}
          pagination={{
            current: Number(this.state.page) + 1,
            loading: this.props.isLoading,
            pageSize: Number(this.state.pagesize),
            showSizeChanger: true,
            showQuickJumper: false,
            pageSizeOptions: ['1', '5', '10', '20', '50'],
            total: this.props.total,
            onShowSizeChange: (current, size) => {
              that.setState({ pagesize: size, page: 0 }, () => {
                that.reloadData();
              });
            },
            onChange: (page, pageSize) => {
              that.setState({ page: page - 1 }, () => {
                that.reloadData();
              });
            },
            showTotal: total => `总计 ${total} 条`,
          }}
          dataSource={this.props.list}
        />

        <Modal
          mask={false}
          title="会员卡充值"
          visible={this.state.isShowInoutMoneyModal}
          onOk={() => {
            var totalPrice = parseInt(that.state.optmoney)+parseInt(that.state.givemoney)+parseInt(that.state.card.totalMoney)
                that.props.updateVipCard({
                  id:that.state.card._id,
                  totalMoney:totalPrice,
                  isMoney:1
                },res=>{
                  message.success('充值成功')
                  that.setState({isShowInoutMoneyModal:false})
                  this._getVipCardList()
                  that.props.addVipCardHistory({
                    cardId:that.state.card.cardId,
                    optType:'0',
                    optDesc:'普通充值',
                    optMoney: that.state.optmoney,
                    giveMoney:that.state.givemoney,
                    totalMoney:totalPrice,
                    owner:that.state.shopTel,
                  })
                })



          }}
          onCancel={() => {
            that.setState({ isShowInoutMoneyModal: false });
          }}
          okText="确认"
          cancelText="取消"
        >
          <Row >
            <Col span={8}>
              <span>充值金额</span>
            </Col>
            <Col span={16}>
              <InputNumber
                defaultValue={that.state.optmoney}
                min={0}
                onChange={e => {
                  that.setState({ optmoney: e });
                }}
                ref="optmoney"
              />
            </Col>
            <Col span={8}>
              <span>赠送金额</span>
            </Col>
            <Col span={16}>
              <InputNumber
                defaultValue={that.state.givemoney}
                min={0}
                onChange={e => {
                  that.setState({ givemoney: e});
                }}
                ref="givemoney"
              />
            </Col>
          </Row>


        </Modal>

        <Modal
          mask={false}
          title="添加会员套餐"
          visible={this.state.isShowAddTcModal}
          onOk={() => {
            that.setState({ isShowAddTcModal: false });
          }}
          onCancel={() => {
            that.setState({ isShowAddTcModal: false });
          }}
          okText="确认"
          cancelText="取消"
        >
          <Row >
            <List
              bordered
              dataSource={that.props.templateList}
              renderItem={item => (<span>
                <Row >
                  <Col span={9}>
                    <span>{item.name} </span>
                  </Col>
                  <Col span={9}>
                    <span>¥{item.price}</span>
                  </Col>
                  <Col span={6}>
                      <div
                        onClick={()=>{

                          that.props.addPackage({
                            ...item,
                            carderId:that.state.card.cardId,
                            contactId:that.state.card.cardId},newPackage=>{
                            if(newPackage == undefined){
                              return
                            }
                            var arr = that.state.card.packageItems.map(cell=>{
                              return cell._id
                            })
                            arr.push(newPackage.ret._id)
                            that.setState({isShowAddTcModal:false})

                            that.props.updateVipCard({
                              id:that.state.card._id,
                              packageItems:arr,
                              isMoney:0,
                              contactId:that.state.card.cardId,
                            },res=>{
                              message.success('添加成功')
                              this._getVipCardList()

                              that.props.addVipCardHistory({
                                cardId:that.state.card.cardId,
                                optType:'1',
                                optDesc:'新增套餐:'+item.name,
                                optMoney: item.price,
                                giveMoney:'0',
                                totalMoney:item.price,
                                owner:this.state.shopTel,
                              })
                            })
                          })

                        }}
                      >

                      <Button size={"small"}
                              type="primary">
                        添加
                      </Button>
                      </div>
                  </Col>
                </Row>

                </span>)}
            />
          </Row>


        </Modal>
      </div>
      </Card>
    );
  }
}
